const jwt = require('jsonwebtoken');

// 在真实生产环境中，这个密钥应该来自环境变量
const JWT_SECRET = require('crypto').randomBytes(64).toString('hex');

const verifyToken = (req, res, next) => {
    const authHeader = req.headers['authorization'];
    const token = authHeader && authHeader.split(' ')[1]; // Bearer TOKEN

    if (!token) {
        return res.sendStatus(401); // Unauthorized
    }

    jwt.verify(token, JWT_SECRET, (err, user) => {
        if (err) {
            return res.sendStatus(403); // Forbidden
        }
        req.user = user;
        next();
    });
};

module.exports = { verifyToken, JWT_SECRET };